<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller {

	function __construct()
	{
		parent::__construct();
//		$this->output->enable_profiler(TRUE);

		$this->load->model('City_m','city');
		$this->load->model('dx_auth/Users', 'users');
		$this->load->model('Admin_m','admin');
		$this->load->model('Site_m','site');
		$this->load->model('Category_m','category');

		$is_login = $this->dx_auth->is_logged_in();
		if(!$is_login || !($this->dx_auth->is_admin())){
			redirect('', 'location');
		}

		$this->load->helper('url');
	}

	// AJAX interface
	function user_view(){
		$start = intval($this->input->post('start', TRUE));
		$limit = intval($this->input->post('limit', TRUE));
		$query = $this->input->post('query', TRUE);
		$all_users = $this->users->get_all($start, $limit, $query);
		$res = array();
		$res['data'] = array();
		$res['total'] = $this->users->get_total_user($query);
		foreach ($all_users->result() as $row)
		{
			$iuser = array();
			$iuser['id'] = $row->id;
			$iuser['username'] = $row->username;
			$iuser['email'] = $row->email;
			$iuser['role_id'] = $row->role_id == 2 ? '管理员' : '普通用户';
			$res['data'][] = $iuser;
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function user_update(){
		$res = array();
		$res['success'] = FALSE;
		$res['message'] = 'failed';

		$update_data = $this->admin->process_user_post_data($this->input->post('data'));
		if (count($update_data) > 0){
			foreach ($update_data as $idata)
			{
				$this->users->set_role($idata->id, $idata->role_id);
			}
			$user_count = count($update_data);
			$res['success'] = TRUE;
			$res['message'] = "Updated $user_count site(s).";
			$res['data'] = json_decode($this->input->post('data'));
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function user_destroy(){
		$res = array();
		$res['success'] = FALSE;
		$ids = json_decode($this->input->post('data'));
		if (! is_array($ids)){
			if (strlen($this->input->post('data')) > 0){
				$post_id = intval(str_replace('"', '', $this->input->post('data')));
				$ids = array($post_id);
			}
		}
		if (count($ids) > 0){
			foreach($ids as $id){
				$this->users->delete_user($id);
			}
			$user_count = count($ids);
			$res['success'] = TRUE;
			$res['message'] = "Deleted $user_count user(s).";
		}
		$this->_echo_json($res);
	}


	// AJAX interface
	function site_view(){
		$start = intval($this->input->post('start', TRUE));
		$limit = intval($this->input->post('limit', TRUE));
		$query = $this->input->post('query', TRUE);
		$all_sites = $this->site->get_paged_site($start, $limit, $query);
		$res = array();
		$res['data'] = array();
		$res['total'] = $this->site->get_total_site($query);
		$datas = $this->_site_transform_to_extjs_data($all_sites->result());
		$res['data'] = $datas;
		$this->_echo_json($res);
	}

	// AJAX interface
	function site_destroy()	{
		$res = array();
		$res['success'] = FALSE;
		$ids = json_decode($this->input->post('data'));
		if (! is_array($ids)){
			if (strlen($this->input->post('data')) > 0){
				$post_id = intval(str_replace('"', '', $this->input->post('data')));
				$ids = array($post_id);
			}
		}
		if (count($ids) > 0){
			foreach($ids as $id){
				$this->site->delete_site($id);
			}
			$site_count = count($ids);
			$res['success'] = TRUE;
			$res['message'] = "Deleted $site_count site(s).";
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function site_create()	{
		$return_ids = array();
		$res = array();
		$res['success'] = FALSE;
		$res['message'] = 'failed';
		$update_data = $this->admin->process_site_post_data($this->input->post('data'));
		if (count($update_data) > 0){
			if ($this->_verify_post_data_url($update_data))			{
				foreach ($update_data as $idata)
				{
					$ret_id = $this->site->create_site((array) $idata);
					if ($ret_id > 0){
						$return_ids[] = $ret_id;
					}
				}

				$resdata = array();
				$return_ids = array_reverse($return_ids);
				foreach($return_ids as $ret_id)
				{
					$resdata[] = $this->_site_transform_to_extjs_data($this->site->get_site(array('id' => $ret_id)));
				}
				if (count($resdata) == 1){
					$one_site = $resdata[0];
					$res['data'] = $one_site;
				} else {
					$res['data'] = $resdata;
				}
				$site_count = count($update_data);
				$res['success'] = TRUE;
				$res['message'] = "Created $site_count site(s).";
			}
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function site_update(){
		$res = array();
		$res['success'] = FALSE;
		$res['message'] = 'failed';

		$update_data = $this->admin->process_site_post_data($this->input->post('data'));
		if (count($update_data) > 0){
			if ($this->_verify_post_data_url($update_data))	{
				foreach ($update_data as $idata)
				{
					if ($idata->launch == '启动'){
						$ssid = $idata->id;
						$tail_url = "cron/craw/$ssid";
						$craw_url = site_url("$tail_url");
						$ch = curl_init();
						curl_setopt( $ch, CURLOPT_URL, $craw_url );
						curl_setopt( $ch, CURLOPT_TIMEOUT, 120 );
						$content = curl_exec( $ch );
						curl_close ( $ch );
						$site_count = count($update_data);
						$res['success'] = TRUE;
						$res['message'] = "Craw $site_count site(s).";
					} else {
						$this->site->update_site($idata->id, $idata);
						$site_count = count($update_data);
						$res['success'] = TRUE;
						$res['message'] = "Updated $site_count site(s).";
					}
				}
				$res['data'] = json_decode($this->input->post('data'));
			}
		}
		$this->_echo_json($res);
	}

	function _verify_post_data_url($data){
		$res = TRUE;
		foreach($data as $idata)
		{
			$res = $res && $this->_is_url($idata->site_url);
			$res = $res && $this->_is_url($idata->xml_url);
			if (strlen($idata->site_mail) > 0){
				$res = $res && $this->_is_email($idata->site_mail);
			}

			if (strlen($idata->site_tel) > 0){
				$res = $res && $this->_is_tel($idata->site_tel);
			}

			if (! $res){
				break;
			}
		}
		return $res;
	}

	function _is_tel($tel){
		if (ereg("^((\([0-9]{3,4}\)[ -]?)|([0-9]{3,4}[- ]))?[0-9]{3,4}[- ]?[0-9]{6,8}$", $tel)){
			return TRUE;
		} else {
			return FALSE;
		}
	}

	function _is_email($email){
		return strlen($email) > 6 && (1 === preg_match("/^[\w\-\.]+@[\w\-]+(\.\w+)+$/", $email));
	}

	function _is_url($str){
		return 1 === preg_match("/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"])*$/", $str);
	}

	function _tag_transform_to_extjs_data($datas){
		$res = array();
		$all_cats = array_flip($this->category->get_level_one_category());
		foreach ($datas as $row)
		{
			$iuser = array();
			$iuser['id'] = $row['id'];
			$iuser['cat_name'] = $row['cat_name'];
			$iuser['cat_parent'] = $all_cats[$row['cat_parent']];
			$res[] = $iuser;
		}
		return $res;
	}

	function _site_transform_to_extjs_data($datas){
		$res = array();
		$templates = $this->admin->get_all_templates();
		$template_map = array();
		foreach ($templates as $it)
		{
			$template_map[$it->id] = $it->name;
		}
		foreach ($datas as $row)
		{
			$iuser = array();
			$iuser['id'] = $row->id;
			$iuser['site_name'] = $row->site_name;
			$iuser['site_url'] = $row->site_url;
			$iuser['xml_url'] = $row->xml_url;
			$iuser['api_template_id'] = $template_map[$row->api_template_id];
			$iuser['status'] = intval($row->status) == 1 ? '审核通过并抓取' : '待审核';
			$iuser['site_tel'] = $row->site_tel;
			$iuser['weight'] = $row->weight;
			$iuser['site_mail'] = $row->site_mail;
			$iuser['cap'] = $row->cap;
			$iuser['logo_url'] = $row->logo_url;
			$res[] = $iuser;
		}
		return $res;
	}

	// AJAX interface
	function tag_view()	{
		$start = intval($this->input->post('start', TRUE));
		$limit = intval($this->input->post('limit', TRUE));
		$query = $this->input->post('query', TRUE);
		$all_cats = $this->category->get_level_two_category($start, $limit, $query);
		$res = array();
		$res['data'] = array();
		$res['total'] = $this->category->get_total_level_two_category($query);
		foreach ($all_cats->result() as $row)
		{
			$iuser['id'] = $row->id;
			$iuser['cat_name'] = $row->cat_name;
			$iuser['cat_parent'] = $row->cat_parent;
			$res['data'][] = $iuser;
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function tag_update(){
		$res = array();
		$res['success'] = FALSE;
		$res['message'] = 'failed';

		$update_data = $this->admin->process_tag_post_data($this->input->post('data'));
		if (count($update_data) > 0){
			foreach ($update_data as $idata)
			{
				$this->category->update_category($idata);
			}
			$tag_count = count($update_data);
			$res['success'] = TRUE;
			$res['message'] = "Updated $tag_count tag(s).";
			$res['data'] = json_decode($this->input->post('data'));
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function tag_destroy(){
		$res = array();
		$res['success'] = FALSE;
		$ids = json_decode($this->input->post('data'));
		if (! is_array($ids)){
			if (strlen($this->input->post('data')) > 0){
				$post_id = intval(str_replace('"', '', $this->input->post('data')));
				$ids = array($post_id);
			}
		}
		if (count($ids) > 0){
			$delete_ret = TRUE;
			foreach($ids as $id){
				$delete_ret = $delete_ret && $this->category->delete_category($id);
			}
			$tag_count = count($ids);
			$res['message'] = "Deleted $tag_count tag(s).";
			$res['success'] = $delete_ret;
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function tag_create()
	{
		$return_ids = array();
		$res = array();
		$res['success'] = FALSE;
		$res['message'] = 'failed';
		$update_data = $this->admin->process_tag_post_data($this->input->post('data'));
		if (count($update_data) > 0){
			foreach ($update_data as $idata)
			{
				$ret_id = $this->category->add_lev2cat($idata->cat_name, $idata->cat_parent);
				if ($ret_id > 0){
					$return_ids[] = $ret_id;
				}
			}

			$resdata = array();
			if (count($return_ids) > 0){
				$return_ids = array_reverse($return_ids);
				$resdata[] = $this->category->get_category($return_ids);
				if (count($resdata) == 1){
					$one_site = $resdata[0];
					$res['data'] = $one_site;
				} else {
					$res['data'] = $resdata;
				}

				$res['data'] = $this->_tag_transform_to_extjs_data($res['data']);
				$tag_count = count($update_data);
				$res['success'] = TRUE;
				$res['message'] = "Created $tag_count tag(s).";
			} else {
				$res['success'] = FALSE;
				$res['message'] = "tag duplicate";
			}
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function city_view()	{
		$start = intval($this->input->post('start', TRUE));
		$limit = intval($this->input->post('limit', TRUE));
		$query = $this->input->post('query', TRUE);
		$all_citys = $this->city->get_paged_city($start, $limit, $query);
		$res = array();
		$res['data'] = array();
		$res['total'] = $this->city->get_total_city($query);
		foreach ($all_citys->result() as $row)
		{
			$icity['id'] = $row->id;
			$icity['city'] = $row->city;
			$res['data'][] = $icity;
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function city_create()
	{
		$return_ids = array();
		$res = array();
		$res['success'] = FALSE;
		$res['message'] = 'failed';
		$update_data = $this->admin->process_city_post_data($this->input->post('data'));
		if (count($update_data) > 0){
			foreach ($update_data as $idata)
			{
				$ret_id = $this->city->get_id_by_city($idata->city);
				if (! ($ret_id > 0)){
					$ret_id = $this->city->add_city($idata->city);
					$return_ids[] = $ret_id;
				}
			}

			$resdata = array();
			if (count($return_ids) > 0){
				$return_ids = array_reverse($return_ids);
				$resdata[] = $this->city->get_city_by_ids($return_ids);
				if (count($resdata) == 1){
					$one_site = $resdata[0];
					$res['data'] = $one_site;
				} else {
					$res['data'] = $resdata;
				}

				$tag_count = count($update_data);
				$res['success'] = TRUE;
				$res['message'] = "Created $tag_count city(s).";
			} else {
				$res['success'] = FALSE;
				$res['message'] = "Name duplicate";
			}
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function city_destroy(){
		$res = array();
		$res['success'] = FALSE;
		$ids = json_decode($this->input->post('data'));
		if (! is_array($ids)){
			if (strlen($this->input->post('data')) > 0){
				$post_id = intval(str_replace('"', '', $this->input->post('data')));
				$ids = array($post_id);
			}
		}
		if (count($ids) > 0){
			$delete_ret = TRUE;
			foreach($ids as $id){
				$delete_ret = $delete_ret && $this->city->delete_city($id);
			}
			$tag_count = count($ids);
			$res['message'] = "Deleted $tag_count city(s).";
			$res['success'] = $delete_ret;
		}
		$this->_echo_json($res);
	}

	// AJAX interface
	function city_update(){
		$res = array();
		$res['success'] = FALSE;
		$res['message'] = 'failed';

		$update_data = $this->admin->process_city_post_data($this->input->post('data'));
		if (count($update_data) > 0){
			foreach ($update_data as $idata)
			{
				$this->city->update_city($idata->id, $idata->city);
			}
			$tag_count = count($update_data);
			$res['success'] = TRUE;
			$res['message'] = "Updated $tag_count city(s).";
			$res['data'] = json_decode($this->input->post('data'));
		}
		$this->_echo_json($res);
	}

	function _echo_json($res){
		header('Content-type: application/json');
		echo json_encode($res);
	}


	// url
	function user(){
		$user_data = array(
			'sub_view' => 'user',
		);
		$this->_admin_view($user_data);
	}

	function city(){
		$user_data = array(
			'sub_view' => 'city',
		);
		$this->_admin_view($user_data);
	}

	function tag(){
		$cats = $this->category->get_level_one_category();
		$user_data = array(
			'sub_view' => 'tag',
			'cats' => $cats
		);
		$this->_admin_view($user_data);
	}

	function site(){
		$templates = $this->admin->get_common_templates();
		$template_arr = array();
		foreach ($templates as $it)
		{
			$template_arr[] = $it->name;
		}
		$user_data = array(
			'sub_view' => 'site',
			'templates' => $template_arr
		);

		$this->_admin_view($user_data);
	}

	function _admin_view($input_data){
		$user_id = $this->dx_auth->get_user_id();
		$is_login = $this->dx_auth->is_logged_in();
		$this->load->model('City_m','city');
		$all_city = $this->city->get_all_from_config();

		$base_data = array(
			'is_login' => $is_login,
			'all_city' => $all_city,
			'post_email' => '',
			'templates' => '',
			'post_err' => ''
			);

		$data = array_merge($base_data, $input_data);

		$this->load->view('admin', $data);
	}

	function index(){
		$this->user();
	}

	// delete this function before release
	function reg($name){
		$ret = 'fail...';
		if ($name and strlen($name) > 0)
		{
			$ret = $this->dx_auth->register($name, '111111', "${name}@tuan.com");
		}
		var_dump($ret);
	}

	function goods($site_id=0, $is_publish=false, $keyword='-',$offset=0){
		$this->load->model('Site_m','site');
		$this->load->model('Goods_m','goods');

		$all_site = $this->site->get_all_site();

		$real_kw = $this->input->post('keyword');
		if($real_kw){
			$keyword = $real_kw;
		}else{
			$keyword = $keyword=='-'?'':urldecode($keyword);
			$this->load->library('security');
			$keyword = $this->security->xss_clean(trim($keyword));
		}

		$total_count = $this->goods->get_site_goods_count($site_id,$is_publish,$keyword);

		$all_city_map = array();
		$cat_info = array();
		$goods = array();
		if($total_count > 0){
				$all_city_map = $this->city->get_all_map();
				$cat_info = $this->category->get_all_category();
				$goods = $this->goods->get_site_goods($site_id,$is_publish,$keyword,$offset,NUM_PER_PAGE,'close_time asc');
		}

		$this->load->library('pagination');
		$base_url = site_url("/admin/goods/$site_id/".($is_publish?'1':'0').'/'.($keyword?urlencode($keyword):'-').'/');
		$pg_config['base_url'] = $base_url;
		$pg_config['total_rows'] = $total_count;
		$pg_config['per_page'] = NUM_PER_PAGE;
		$pg_config['uri_segment'] = 6;
		$this->pagination->initialize($pg_config);
		$page_links = $this->pagination->create_links();

		$data = array(
				'total_count' => $total_count,
				'goods' => $goods,
				'all_site' => $all_site,
				'all_city_map' => $all_city_map,
				'cat_info' => $cat_info,
				'page_links' => $page_links,
				'site_id' => $site_id,
				'is_publish' => $is_publish,
				'keyword' => $keyword
				);

		$this->load->view('admin/goods', $data);
	}
	
	function suggestion($offset = 0){
		$this->load->model('Suggest_m','sugg');
		$count = $this->sugg->get_count();
		$suggestion = array();
		if($count){
			$suggestion = $this->sugg->get_paged_suggestion($offset,NUM_PER_PAGE);
		}
		
		$this->load->library('pagination');
		$base_url = site_url('/admin/suggestion/');
		$pg_config['base_url'] = $base_url;
		$pg_config['total_rows'] = $count;
		$pg_config['per_page'] = NUM_PER_PAGE;
		$pg_config['uri_segment'] = 3;
		$this->pagination->initialize($pg_config);
		$page_links = $this->pagination->create_links();
		
		$data = array(
				'suggestion' => $suggestion,
				'page_links' => $page_links
				);
		$this->load->view('admin/suggestion', $data);
	}

	function puball($site_id=0, $keyword='-'){
		$this->_set_all_good_publish($site_id,$keyword,true);
	}

	function unpuball($site_id=0, $keyword='-'){
		$keyword = $keyword=='-'?'':urldecode($keyword);
		$this->load->library('security');
		$keyword = $this->security->xss_clean(trim($keyword));
		$this->_set_all_good_publish($site_id,$keyword,false);
	}

	function _set_all_good_publish($site_id=0, $keyword='-',$is_publish=true){
		$this->load->library('security');
		$keyword = $keyword=='-'?'':urldecode($keyword);
		$keyword = $this->security->xss_clean(trim($keyword));

		$this->load->model('Goods_m','goods');
		$this->goods->set_goods_publish($site_id,$keyword,$is_publish);

		redirect('admin/goods/'.$site_id.'/'.($is_publish?0:1).'/'.urlencode($keyword));
	}

	function childcat($parent_cat_id){
		$ret = array();
		if(isset($parent_cat_id) && intval($parent_cat_id) >= -1){
			$parent_cat_id = intval($parent_cat_id);
			$ret = $this->category->get_child_category($parent_cat_id);
		}
		echo json_encode($ret);
	}

	function addlev2cat($name, $parent=-2){
		$ret = false;
		$this->load->library('security');
		$name = $this->security->xss_clean(urldecode(urldecode(trim($name))));
		$parent = intval($parent);
		if($name && $parent >= -1){
			$ret = $this->category->add_lev2cat($name, $parent);
		}

		echo json_encode(array('ret' => $ret));
	}

	function delgood($good_id=0,$site_id=0, $is_publish=false, $keyword='-'){
		$ret = false;
		$good_id = intval($good_id);
		if($good_id > 0){
			$this->load->model('Goods_m','goods');
			$ret = $this->goods->delete_good($good_id);
		}
//		echo json_encode(array('ret' => $ret));
		redirect(site_url('admin/goods/'.$site_id.'/'.($is_publish?1:0).'/'.$keyword));
	}

	function _set_good_publish($good_id=0, $is_publish = true){
		$ret = false;
		$good_id = intval($good_id);
		if($good_id > 0){
			$this->load->model('Goods_m','goods');
			$ret = $this->goods->set_good($good_id,array('is_publish' => $is_publish?1:0));
		}
//		echo json_encode(array('ret' => $ret));
	}

	function pubgood($good_id=0,$site_id=0, $is_publish=false, $keyword='-'){
		$this->_set_good_publish($good_id,true);
		redirect(site_url('admin/goods/'.$site_id.'/'.($is_publish?1:0).'/'.$keyword));
	}

	function unpubgood($good_id=0,$site_id=0, $is_publish=false, $keyword='-'){
		$this->_set_good_publish($good_id,false);
		redirect(site_url('admin/goods/'.$site_id.'/'.($is_publish?1:0).'/'.$keyword));
	}

	function setcat($good_id, $lev1cat, $lev2cat){
		$good_id = intval($good_id);
		$ret = array('ret' => false);
		if($good_id > 0){
			$data = array(
						'cat_level1' => intval($lev1cat),
						'cat_level2' => intval($lev2cat)
						);
			$this->load->model('Goods_m','goods');
			$this->goods->set_good($good_id,$data);
			$ret['ret'] = true;
		}
		echo json_encode($ret);
	}
}
